<template>
  <div class="match-integrated-container">
    <!-- 页面标题和全局操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">三单匹配</h2>
      <div class="header-buttons">
        <div class="button-group primary-group">
          <el-button type="primary" @click="handleGlobalMatch">
            <el-icon>
              <Connection/>
            </el-icon>
            全局匹配
          </el-button>
          <el-button type="primary" @click="handleManualMatch">
            <el-icon>
              <Plus/>
            </el-icon>
            手动匹配
          </el-button>
          <el-button type="primary" @click="refreshData">
            <el-icon>
              <Refresh/>
            </el-icon>
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索表单区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline label-width="100px" @keyup.enter="handleSearch">
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.orderStatus" clearable placeholder="请选择订单状态" style="width: 180px">
            <el-option label="全部" value=""></el-option>
            <el-option label="待收货" value="PENDING_RECEIPT"></el-option>
            <el-option label="已收货" value="RECEIVED"></el-option>
            <el-option label="已开票" value="INVOICED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单据编号">
          <el-input v-model="searchForm.documentNumber" clearable placeholder="订单号/发票号/收货单号"></el-input>
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="searchForm.supplierName" clearable placeholder="供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="采购日期">
          <el-date-picker
              v-model="searchForm.dateRange"
              :shortcuts="dateShortcuts"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon>
              <Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Tab页和数据展示区 -->
    <el-card class="tab-card">
      <!-- 表格操作按钮 -->
      <div class="table-operations">
        <el-button :disabled="selectedItems.length === 0" type="danger" @click="handleBatchDelete">
          <el-icon>
            <Delete/>
          </el-icon>
          批量删除
        </el-button>
        <!--        todo 删除导出-->
        <!--        <el-button type="success" @click="exportMatchData">-->
        <!--          <el-icon>-->
        <!--            <Download/>-->
        <!--          </el-icon>-->
        <!--          导出数据-->
        <!--        </el-button>-->
      </div>

      <el-table
          v-loading="availableLoading"
          :data="availableOrders"
          border
          stripe
          style="width: 100%"
          @selection-change="handleAvailableSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="订单编号" min-width="120" prop="orderNumber"></el-table-column>
        <el-table-column label="供应商" min-width="150" prop="supplierName"></el-table-column>
        <el-table-column label="金额" min-width="100" prop="totalAmount">
          <template #default="scope">
            {{ formatCurrency(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="采购日期" min-width="120" prop="purchaseDate"></el-table-column>
        <el-table-column label="状态" min-width="100" prop="status">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ mapStatusForDisplay(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="170" prop="createTime"></el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleMatchOrder(scope.row)">匹配</el-button>
            <el-button size="small" @click="handleViewOrder(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="availableCurrentPage"
            v-model:page-size="availablePageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="availableTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleAvailableSizeChange"
            @current-change="handleAvailableCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 匹配详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        destroy-on-close
        title="匹配详情"
        width="80%"
    >
      <div v-if="currentDetail" v-loading="detailLoading" class="match-detail-content">
        <el-descriptions :column="2" border title="单据信息">
          <el-descriptions-item label="匹配ID">{{ currentDetail.matchId || '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="匹配状态">
            <el-tag :type="getTagType(currentDetail.matchResult)">
              {{ currentDetail.matchResult || '未知状态' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单编号">{{ currentDetail.orderNumber || '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">
            {{ formatCurrency(currentDetail.orderAmount) || '0.00' }}
          </el-descriptions-item>
          <el-descriptions-item label="收货单编号">{{ currentDetail.receiptNumber || '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="收货单金额">
            {{ formatCurrency(currentDetail.receiptAmount) || '0.00' }}
          </el-descriptions-item>
          <el-descriptions-item label="发票编号">{{ currentDetail.invoiceNumber || '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="发票金额">
            {{ formatCurrency(currentDetail.invoiceAmount) || '0.00' }}
          </el-descriptions-item>
          <el-descriptions-item label="供应商名称">{{ currentDetail.supplierName || '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="匹配时间">{{ currentDetail.matchTime || '暂无' }}</el-descriptions-item>
          <el-descriptions-item :span="2" label="差异信息">
            {{ currentDetail.difference || '无差异' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 匹配候选对话框 -->
    <el-dialog v-model="matchCandidatesDialog" title="选择匹配候选项" width="800px">
      <el-form :model="matchCandidates" label-width="120px">
        <el-form-item label="订单信息">
          <div class="order-info">
            <div><strong>订单编号:</strong> {{ selectedOrderInfo?.orderNumber }}</div>
            <div><strong>供应商:</strong> {{ selectedOrderInfo?.supplierName }}</div>
            <div><strong>金额:</strong> {{ formatCurrency(selectedOrderInfo?.totalAmount) }}</div>
          </div>
        </el-form-item>
        <el-form-item label="可匹配的收货单">
          <el-select v-model="selectedReceiptId" filterable placeholder="请选择收货单">
            <el-option
                v-for="item in matchCandidates.receipts"
                :key="item.id"
                :label="`${item.receiptNumber} - ${item.supplierName} - ${formatCurrency(item.totalAmount)}元`"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可匹配的发票">
          <el-select v-model="selectedInvoiceId" filterable placeholder="请选择发票">
            <el-option
                v-for="item in matchCandidates.invoices"
                :key="item.id"
                :label="`${item.invoiceNumber} - ${item.supplierName} - ${formatCurrency(item.totalAmount)}元`"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="matchCandidatesDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmOrderMatch">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 手动匹配对话框 -->
    <el-dialog v-model="matchDialogVisible" title="三单匹配" width="650px">
      <el-form :model="matchForm" label-width="120px">
        <el-form-item label="订单">
          <el-select v-model="matchForm.orderId" filterable placeholder="请选择订单" @change="handleOrderSelectChange">
            <template v-if="orderOptions.length > 0">
              <el-option
                  v-for="item in orderOptions"
                  :key="item.id ? item.id.toString() : ''"
                  :label="item.orderNumber ? `${item.orderNumber} - ${item.supplierName || ''}` : '未知订单'"
                  :value="item.id ? item.id.toString() : ''"
              ></el-option>
            </template>
            <el-option v-else disabled label="暂无可选订单" value=""></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收货单">
          <el-select v-model="matchForm.receiptId" filterable placeholder="请选择收货单">
            <template v-if="receiptOptions.length > 0">
              <el-option
                  v-for="item in receiptOptions"
                  :key="item.id ? item.id.toString() : ''"
                  :label="item.receiptNumber ? `${item.receiptNumber} - ${item.supplierName || ''}` : '未知收货单'"
                  :value="item.id ? item.id.toString() : ''"
              ></el-option>
            </template>
            <el-option v-else disabled label="暂无可选收货单" value=""></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票">
          <el-select v-model="matchForm.invoiceId" filterable placeholder="请选择发票">
            <template v-if="invoiceOptions.length > 0">
              <el-option
                  v-for="item in invoiceOptions"
                  :key="item.id ? item.id.toString() : ''"
                  :label="item.invoiceNumber ? `${item.invoiceNumber} - ${item.supplierName || ''}` : '未知发票'"
                  :value="item.id ? item.id.toString() : ''"
              ></el-option>
            </template>
            <el-option v-else disabled label="暂无可选发票" value=""></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="matchDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitMatch">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 全局匹配结果对话框 -->
    <el-dialog v-model="globalMatchDialogVisible" title="全局匹配结果" width="800px">
      <div v-if="globalMatchResults.length === 0" class="no-data">
        <el-empty description="没有找到可匹配的数据"></el-empty>
      </div>
      <el-table v-else :data="globalMatchResults" border style="width: 100%">
        <el-table-column label="订单编号" min-width="120" prop="orderNumber"></el-table-column>
        <el-table-column label="收货单编号" min-width="120" prop="receiptNumber"></el-table-column>
        <el-table-column label="发票编号" min-width="120" prop="invoiceNumber"></el-table-column>
        <el-table-column label="供应商" min-width="150" prop="supplierName"></el-table-column>
        <el-table-column label="匹配结果" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.matchResult === '匹配' ? 'success' : 'danger'">
              {{ scope.row.matchResult }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="globalMatchDialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click="refreshData">刷新数据</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Connection, Delete, Plus, Refresh, Search} from '@element-plus/icons-vue';
import {batchDeleteMatch, createMatch, getMatchCandidates, getOrdersAvailableForMatch, globalMatch} from '@/api/match';
import {useRouter} from 'vue-router';

const router = useRouter();

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 状态变量
const searchForm = reactive({
  orderStatus: '',
  documentNumber: '',
  supplierName: '',
  dateRange: [] as string[],
});

// 匹配记录相关状态不再需要
const selectedItems = ref<any[]>([]);

// 详情对话框相关状态
const detailDialogVisible = ref(false);
const currentDetail = ref<any>(null);
const detailLoading = ref(false);

// 待匹配订单相关状态
const availableOrders = ref<any[]>([]);
const availableCurrentPage = ref(1);
const availablePageSize = ref(10);
const availableTotal = ref(0);
const availableLoading = ref(false);
// const selectedAvailableItems = ref<any[]>([]);

// 匹配候选对话框相关状态
const matchCandidatesDialog = ref(false);
const selectedOrderId = ref('');
const selectedOrderInfo = ref<any>(null);
const matchCandidates = ref({
  receipts: [] as any[],
  invoices: [] as any[],
  receiptCount: 0,
  invoiceCount: 0
});
const selectedReceiptId = ref('');
const selectedInvoiceId = ref('');

// 手动匹配对话框相关状态
const matchDialogVisible = ref(false);
const matchForm = reactive({
  orderId: '',
  receiptId: '',
  invoiceId: ''
});
const orderOptions = ref<any[]>([]);
const receiptOptions = ref<any[]>([]);
const invoiceOptions = ref<any[]>([]);

// 全局匹配对话框相关状态
const globalMatchDialogVisible = ref(false);
const globalMatchResults = ref<any[]>([]);

// 全局状态变量，用于存储筛选后的完整数据集
const filteredRecords = ref<any[]>([]);

// 状态值映射函数，将后端状态值转换为前端显示的中文状态
const mapStatusForDisplay = (status: string): string => {
  // 如果状态值为空，返回"未知状态"
  if (!status) return '未知状态';

  // 已知的英文状态映射为中文
  switch (status) {
    case 'PENDING_RECEIPT':
      return '待收货';
    case 'RECEIVED':
      return '已收货';
    case 'INVOICED':
      return '已开票';
  }

  // 如果是中文状态，直接返回
  if (status === '待收货' || status === '已收货' || status === '已开票') {
    return status;
  }

  // 其他情况（脏数据），返回"其他状态"
  return '其他状态';
};

// 计算属性，用于待匹配订单API查询参数
const availableQueryParams = computed(() => {
  return {
    supplierName: searchForm.supplierName,
    orderNumber: searchForm.documentNumber,
    startDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[0] : '',
    endDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[1] : '',
    pageNum: availableCurrentPage.value,
    pageSize: availablePageSize.value,
    status: searchForm.orderStatus || '' // 直接使用表单中的状态值
  };
});

// 格式化货币
const formatCurrency = (value: number | undefined) => {
  if (!value && value !== 0) return '0.00';
  return Number(value).toFixed(2);
};

// 获取标签类型
const getTagType = (status: string) => {
  switch (status) {
    case '匹配成功':
      return 'success';
    case '部分匹配':
      return 'warning';
    case '待匹配':
      return 'info';
    case '匹配异常':
      return 'danger';
    case '匹配':
      return 'success';
    case '不匹配':
      return 'danger';
    default:
      return 'info';
  }
};

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case '待收货':
    case 'PENDING_RECEIPT':
      return 'warning';
    case '已收货':
    case 'RECEIVED':
      return 'success';
    case '已开票':
    case 'INVOICED':
      return 'primary';
    default:
      return 'info';
  }
};

// 方法定义
const handleSearch = () => {
  // 执行搜索，重置页码并重新加载数据
  availableCurrentPage.value = 1;

  // 清空筛选后的数据集（会在getAvailableOrders中重新填充）
  filteredRecords.value = [];

  getAvailableOrders();
};

const resetSearch = () => {
  // 重置搜索条件
  searchForm.orderStatus = '';
  searchForm.documentNumber = '';
  searchForm.supplierName = '';
  searchForm.dateRange = [];

  // 清空筛选后的数据集
  filteredRecords.value = [];

  // 重置页码
  availableCurrentPage.value = 1;

  // 重新加载数据
  getAvailableOrders();
};

// 待匹配订单表格选择项变化
const handleAvailableSelectionChange = (selection: any[]) => {
  selectedItems.value = selection;
};

// 待匹配订单分页相关方法
const handleAvailableSizeChange = (val: number) => {
  availablePageSize.value = val;

  // 如果有状态筛选，则使用前端分页
  if (searchForm.orderStatus) {
    availableOrders.value = handleFrontendPagination(
        filteredRecords.value,
        availableCurrentPage.value,
        availablePageSize.value
    );
  } else {
    // 否则重新请求后端数据
    getAvailableOrders();
  }
};

const handleAvailableCurrentChange = (val: number) => {
  availableCurrentPage.value = val;

  // 如果有状态筛选，则使用前端分页
  if (searchForm.orderStatus) {
    availableOrders.value = handleFrontendPagination(
        filteredRecords.value,
        availableCurrentPage.value,
        availablePageSize.value
    );
  } else {
    // 否则重新请求后端数据
    getAvailableOrders();
  }
};

// 处理前端分页
const handleFrontendPagination = (allRecords: any[], currentPage: number, pageSize: number) => {
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  return allRecords.slice(startIndex, endIndex);
};

// 获取待匹配订单
const getAvailableOrders = () => {
  availableLoading.value = true;

  // 获取未过滤的状态参数，用于前端筛选
  const selectedStatus = searchForm.orderStatus;

  // 发送请求时不包含状态参数，在前端进行筛选
  const queryParams = {
    supplierName: availableQueryParams.value.supplierName,
    orderNumber: availableQueryParams.value.orderNumber,
    startDate: availableQueryParams.value.startDate,
    endDate: availableQueryParams.value.endDate,
    // 如果需要前端筛选，请求更多数据
    pageNum: selectedStatus ? 1 : availableQueryParams.value.pageNum,
    pageSize: selectedStatus ? 1000 : availableQueryParams.value.pageSize // 当有状态筛选时，获取更多数据
  };

  getOrdersAvailableForMatch(queryParams)
      .then((res: any) => {
        if (res.code === 200) {
          // 获取所有记录
          let allRecords = res.data.records || [];
          let totalCount = res.data.total || 0;

          // 如果选择了状态，在前端进行筛选
          if (selectedStatus) {
            // 筛选符合所选状态的记录
            allRecords = allRecords.filter(record => {
              // 根据中文或英文状态值进行匹配
              return record.status === selectedStatus ||
                  mapStatusForDisplay(record.status) === mapStatusForDisplay(selectedStatus);
            });

            totalCount = allRecords.length;

            // 前端分页
            availableOrders.value = handleFrontendPagination(
                allRecords,
                availableCurrentPage.value,
                availablePageSize.value
            );
          } else {
            // 没有状态筛选，直接使用后端分页
            availableOrders.value = allRecords;
          }

          // 更新总数
          availableTotal.value = totalCount;

          // 更新全局状态变量
          filteredRecords.value = allRecords;
        } else {
          ElMessage.error(res.message || '获取可匹配订单失败');
        }
      })
      .catch(() => {
        ElMessage.error('获取可匹配订单失败');
      })
      .finally(() => {
        availableLoading.value = false;
      });
};

// 查看匹配详情
// const viewDetail = (row: any) => {
//   detailDialogVisible.value = true;
//   detailLoading.value = true;
//   currentDetail.value = null;
//
//   getMatchDetail(row.id)
//       .then((res: any) => {
//         if (res.code === 200) {
//           currentDetail.value = res.data;
//         } else {
//           ElMessage.error(res.message || '获取匹配详情失败');
//         }
//       })
//       .catch(() => {
//         ElMessage.error('获取匹配详情失败');
//       })
//       .finally(() => {
//         detailLoading.value = false;
//       });
// };

// 删除匹配记录
// const handleDelete = (row: any) => {
//   ElMessageBox.confirm('确定要删除该匹配记录吗?', '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning',
//   })
//       .then(() => {
//         deleteMatch(row.id)
//             .then((res: any) => {
//               if (res.code === 200) {
//                 ElMessage.success('删除成功');
//                 getAvailableOrders();
//               } else {
//                 ElMessage.error(res.message || '删除失败');
//               }
//             })
//             .catch(() => {
//               // 取消删除
//             });
//       })
//       .catch(() => {
//         // 取消删除
//       });
// };

// 批量删除匹配记录
const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 条匹配记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        const ids = selectedItems.value.map(item => item.id);
        batchDeleteMatch(ids)
            .then((res: any) => {
              if (res.code === 200) {
                ElMessage.success('批量删除成功');
                getAvailableOrders();
              } else {
                ElMessage.error(res.message || '批量删除失败');
              }
            })
            .catch(() => {
              // 取消删除
            });
      })
      .catch(() => {
        // 取消删除
      });
};

// 表格选择项变化
// const handleSelectionChange = (selection: any[]) => {
//   selectedItems.value = selection;
// };

// 处理匹配操作
const handleMatchOrder = (order: any) => {
  selectedOrderId.value = order.id;
  selectedOrderInfo.value = order;
  matchCandidatesDialog.value = true;
  selectedReceiptId.value = '';
  selectedInvoiceId.value = '';

  // 获取与该订单可匹配的收货单和发票
  getMatchCandidates(order.id)
      .then((res: any) => {
        if (res.code === 200) {
          matchCandidates.value = res.data;

          // 检查返回的数据是否为空
          if ((!res.data.receipts || res.data.receipts.length === 0) &&
              (!res.data.invoices || res.data.invoices.length === 0)) {
            ElMessage.warning('系统中没有找到可匹配的收货单和发票');
          }
        } else {
          ElMessage.error(res.message || '获取匹配候选项失败');
        }
      })
      .catch(() => {
        ElMessage.error('获取匹配候选项失败');
      });
};

// 确认订单匹配
const confirmOrderMatch = () => {
  if (!selectedOrderId.value) {
    ElMessage.warning('请选择订单');
    return;
  }

  if (!selectedReceiptId.value && !selectedInvoiceId.value) {
    ElMessage.warning('请至少选择一个收货单或发票');
    return;
  }

  // 显示匹配进行中
  ElMessage.info('正在进行匹配操作...');

  createMatch({
    orderId: selectedOrderId.value,
    receiptId: selectedReceiptId.value,
    invoiceId: selectedInvoiceId.value,
    differenceReason: '',
    remark: ''
  })
      .then((res: any) => {
        if (res.code === 200) {
          ElMessage.success('匹配成功');
          matchCandidatesDialog.value = false;
          getAvailableOrders();  // 刷新待匹配订单列表
        } else {
          ElMessage.error(res.message || '匹配失败');
        }
      })
      .catch(() => {
        ElMessage.error('匹配失败');
      });
};

// 查看订单详情
const handleViewOrder = (row: any) => {
  router.push(`/dashboard/order-detail/${row.id}`);
};

// 手动匹配
const handleManualMatch = () => {
  // 打开手动匹配对话框
  matchDialogVisible.value = true;
  matchForm.orderId = '';
  matchForm.receiptId = '';
  matchForm.invoiceId = '';

  // 加载可选订单
  orderOptions.value = availableOrders.value.slice(0, 10);

  // 初始化收货单和发票选项为空
  receiptOptions.value = [];
  invoiceOptions.value = [];

  // 这里应该添加获取可匹配收货单和发票的API调用
  ElMessage.info('请先选择订单，然后系统将加载相应的收货单和发票');
};

// 提交手动匹配
const submitMatch = () => {
  if (!matchForm.orderId || !matchForm.receiptId || !matchForm.invoiceId) {
    ElMessage.warning('请选择要匹配的订单、收货单和发票');
    return;
  }

  createMatch({
    orderId: matchForm.orderId,
    receiptId: matchForm.receiptId,
    invoiceId: matchForm.invoiceId
  })
      .then((res: any) => {
        if (res.code === 200) {
          ElMessage.success('匹配成功');
          matchDialogVisible.value = false;
          getAvailableOrders();  // 刷新待匹配订单列表
        } else {
          ElMessage.error(res.message || '匹配失败');
        }
      })
      .catch(() => {
        ElMessage.error('匹配失败');
      });
};

// 全局匹配
const handleGlobalMatch = () => {
  ElMessageBox.confirm('确定要执行全局匹配吗？系统将自动查找并匹配符合条件的订单、收货单和发票。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        // 执行全局匹配
        globalMatch()
            .then((res: any) => {
              if (res.code === 200) {
                globalMatchResults.value = res.data || [];
                globalMatchDialogVisible.value = true;
                // 刷新当前页面数据
                refreshData();
              } else {
                ElMessage.error(res.message || '全局匹配失败');
              }
            })
            .catch(() => {
              // 取消操作
            });
      })
      .catch(() => {
        // 取消操作
      });
};

// const exportMatchData = () => {
//   // 根据当前筛选条件导出数据
//   const params = {
//     matchResult: searchForm.orderStatus,
//     documentNumber: searchForm.documentNumber,
//     supplierName: searchForm.supplierName,
//     startDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[0] : '',
//     endDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[1] : '',
//   };
//
//   exportMatch(params)
//       .then((res: any) => {
//         // 处理文件下载
//         const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
//         const link = document.createElement('a');
//         link.href = window.URL.createObjectURL(blob);
//         const currentDate = new Date().toISOString().split('T')[0];
//         link.download = `匹配记录_${currentDate}.xlsx`;
//         link.click();
//         window.URL.revokeObjectURL(link.href);
//         ElMessage.success('导出成功');
//       })
//       .catch(() => {
//         ElMessage.error('导出失败');
//       });
// };

const refreshData = () => {
  getAvailableOrders();
};

// 生命周期钩子
onMounted(() => {
  // 初始化加载匹配记录数据
  getAvailableOrders();
});

// 监听手动匹配对话框中的订单选择变化
const handleOrderSelectChange = () => {
  if (matchForm.orderId) {
    // 清空之前的选择
    matchForm.receiptId = '';
    matchForm.invoiceId = '';
    receiptOptions.value = [];
    invoiceOptions.value = [];

    // 加载该订单可匹配的收货单和发票
    ElMessage.info('正在加载可匹配的收货单和发票...');

    getMatchCandidates(matchForm.orderId)
        .then((res: any) => {
          if (res.code === 200) {
            // 更新收货单和发票选项
            receiptOptions.value = res.data.receipts || [];
            invoiceOptions.value = res.data.invoices || [];

            // 检查是否有可匹配项
            if (receiptOptions.value.length === 0 && invoiceOptions.value.length === 0) {
              ElMessage.warning('没有找到可匹配的收货单和发票');
            } else {
              ElMessage.success('已加载可匹配的收货单和发票');
            }
          } else {
            ElMessage.error(res.message || '获取匹配候选项失败');
          }
        })
        .catch(() => {
          ElMessage.error('获取匹配候选项失败');
        });
  }
};
</script>

<style scoped>
.match-integrated-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  margin: 0;
  color: #303133;
}

.header-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.button-group {
  display: flex;
  gap: 10px;
}

.primary-group {
  display: flex;
  gap: 10px;
}

.secondary-group {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-buttons {
    margin-top: 15px;
    width: 100%;
    flex-direction: column;
  }

  .button-group {
    margin-bottom: 10px;
  }
}

.search-card {
  margin-bottom: 20px;
}

.tab-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.order-info {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  background-color: #f9f9f9;
}

.no-data {
  padding: 40px 0;
}

.match-detail-content {
  padding: 20px 0;
}

.table-operations {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

/* 按钮样式 */
:deep(.el-button--danger) {
  background-color: #F56C6C !important;
  border-color: #F56C6C !important;
}

:deep(.el-button--success) {
  background-color: #67C23A !important;
  border-color: #67C23A !important;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989 !important;
  border-color: #f78989 !important;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61 !important;
  border-color: #85ce61 !important;
}

:deep(.el-button--danger:disabled) {
  background-color: #fab6b6 !important;
  border-color: #fab6b6 !important;
  color: white !important;
}
</style> 